package com.theaf.basemodule.service.other;

import com.theaf.core.utils.DateUtils;
import com.theaf.core.utils.ParameterHelper;
import com.theaf.core.utils.SmExceptionHelper;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author:songwenke
 * @Description:短信服务
 * @Date:create in 10:03 2018/3/5
 * @Modified By:
 **/
@Component
public class SmsService {
    /**
     * 发送短信
     * @param phone
     * @param content
     * @return
     * @throws Exception
     */
    public static int sendSms(String phone,String content) throws Exception{
        String autograph = ParameterHelper.getParameterRemark("sms_autographs");
        String pattern = "【[^【^】]+】";
        // 创建 Pattern 对象
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(content);
        boolean ok = true;
        while(m.find()){
            if((","+autograph+",").indexOf(","+content.substring(m.start()+1,m.end()-1)+",")<0){
                ok = false;
                break;
            }
        }
        if(!ok){
            throw SmExceptionHelper.sysCheckException("非法签名");
        }
        if(!Pattern.matches("^1\\d{10}$",phone)){
            throw SmExceptionHelper.sysCheckException(phone+"号码格式不正确");
        }
        String cdkey = ParameterHelper.getParameterRemark("sms_ym_cdkey");
        String pass = cdkey.split("\\:")[1];
        cdkey = cdkey.split("\\:")[0];
        String marketing = ParameterHelper.getParameterRemark("sms_marketing_id");
        if(content.indexOf(marketing)>0){
            cdkey = ParameterHelper.getParameterRemark("sms_ymyx_cdkey");
            pass = cdkey.split("\\:")[1];
            cdkey = cdkey.split("\\:")[0];
        }
        URL url = new URL("http://hprpt2.eucp.b2m.cn:8080/sdkproxy/sendsms.action"
                + "?"+cdkey+"&password="+pass+"&phone="
                +phone+"&message="+ URLEncoder.encode(content));
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestProperty("accept", "*/*");
        con.setRequestProperty("connection", "Keep-Alive");
        con.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        con.connect();
        BufferedReader br = new BufferedReader(new InputStreamReader(con
                .getInputStream(),"UTF-8"));
        String xmlStr = "";
        String line = "";
        for (line = br.readLine(); line != null; line = br.readLine()) {
            xmlStr+=line;
        }
        Document document = DocumentHelper.parseText(xmlStr);
        return Integer.parseInt(document.getRootElement().elementText("error"));
    }

    /**
     * 读短信(phone|time|content)
     * @returnm List<Map>,Map键为phone|time|content,分别表示号码|时间|内容
     * @throws Exception
     */
    public static List<Map> readSms() throws Exception{
        String cdkey = ParameterHelper.getParameterRemark("sms_ym_cdkey");
        String pass = cdkey.split("\\:")[1];
        cdkey = cdkey.split("\\:")[0];
        URL url = new URL("http://hprpt2.eucp.b2m.cn:8080/sdkproxy/getmo.action"
                + "?"+cdkey+"&password="+pass);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestProperty("accept", "*/*");
        con.setRequestProperty("connection", "Keep-Alive");
        con.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        con.connect();
        BufferedReader br = new BufferedReader(new InputStreamReader(con
                .getInputStream(),"UTF-8"));
        String xmlStr = "";
        String line = "";
        for (line = br.readLine(); line != null; line = br.readLine()) {
            xmlStr+=line;
        }
        Document document = DocumentHelper.parseText("<root>"+xmlStr+"</root>");
        Element root = document.getRootElement();
        List<Map> maps = new ArrayList();
        for(Element ele:(List<Element>)root.elements()) {
            Map map = new HashMap();
            map.put("phone",ele.element("srctermid").getData());
            map.put("time", DateUtils.convertStrToDate(ele.element("sendTime").getStringValue(),"yyyyMMddHHmmss"));
            map.put("content",ele.element("msgcontent").getData());
            maps.add(map);
        }
        return maps;
    }
}
